﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Web;
using ChuanYe.DAL;
using ChuanYe.Models;
using ChuanYe.Models.Model;

namespace ChuanYe.Commom
{
    /// <summary>
    ///日志类
    /// </summary>
    public class Log
    {
        //=======【日志级别】===================================
        /* 日志等级，0.不输出日志；1.只输出错误信息; 2.输出错误和操作日志; 3.输出错误信息、正常信息和调试信息
        */
        public static int LOG_LEVENL = int.Parse(DEncrypt.EncryptForConfig.DecryptByAES(System.Configuration.ConfigurationManager.AppSettings["LOG_LEVENL"]));
        //在网站根目录下创建日志目录
        public static string Path = HttpContext.Current.Request.PhysicalApplicationPath + "logs";
        public static string Pathsafe = HttpContext.Current.Request.PhysicalApplicationPath + "logsSafe";

        

        /**
         * 向日志文件写入调试信息
         * @param className 类名
         * @param content 写入内容
         */
        public static void Debug(string className, string content)
        {
            if (LOG_LEVENL >= 3)
            {
                WriteLog(Path, "DEBUG", className, content);
            }
        }

        /**
        * 向数据库写入操作日志
        * @param className 类名
        * @param content 写入内容
        */
        public static void Info(string UID, string ModuleName, string Description)
        {
            if (LOG_LEVENL >= 2)
            {
                WriteInfo(UID, ModuleName, Description);
            }
        }

        /**
        * 向日志文件写入出错信息
        * @param className 类名
        * @param content 写入内容
        */
        public static void Error(string className, string content)
        {
            try
            {
                if (LOG_LEVENL >= 1)
                {
                    WriteLog(Path, "ERROR", className, content);
                }
            }
            catch (Exception e)
            {
                WriteLog(Path, "ERROR", className, content + ">>>" + e.Message);
            }
        }
        /**
        * 写网站攻击日志
        * @param content 写入内容
        */
        public static void Attack(string content)
        {
            WriteLog(Pathsafe, "Attack","",content);
        }

        /**
        * 实际的写日志操作
        * @param type 日志记录类型
        * @param className 类名
        * @param content 写入内容
        */
        protected static void WriteLog(string path, string type, string className, string content)
        {
            if (!Directory.Exists(path))//如果日志目录不存在就创建
            {
                Directory.CreateDirectory(path);
            }

            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");//获取当前系统时间
            string filename = path + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";//用日期对日志文件命名

            //创建或打开日志文件，向日志文件末尾追加记录
            StreamWriter mySw = File.AppendText(filename);

            //向日志文件写入内容
            string write_content = time + " " + type + " " + className + ": " + content;
            mySw.WriteLine(write_content);

            //关闭日志文件
            mySw.Close();
        }
        protected static void WriteInfo(string UID,string ModuleName,string Description)
        {
            try
            {
                UsersInfosDAL DAL = new UsersInfosDAL();
                DocOperationLog model = new DocOperationLog();
                LoginUserModel User = DAL.LoginUserInfos(int.Parse(UID));

                model.AccountCode = User.UserCode;
                model.UserName = User.UserName;
                model.ModuleName = ModuleName;
                model.Description = Description;
                model.indate = DateTime.Now;
                model.UserID = User.ID;
                #region 获取客户端IP
                string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(result))
                {
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = HttpContext.Current.Request.UserHostAddress;
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = "0.0.0.0";
                }
                model.ClientIP = result;
                #endregion

                DAL.DocOperationLogCreate(model);
            }
            catch (Exception ex)
            {
                Error("Log", ex.ToString());
            }
        }
    }
}
